import "ant-design-vue/dist/antd.css";

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store, { resetStore } from "./store";
import { initMicroVueApp } from "common/utils/microApp";
import {
  subscribeGlobalStateChange,
  registerMicroApp,
} from "common/components/basic/app-services/index";
import loadPlugins from "@/core/lazy_use";
import appSettings from "@/config/defaultSettings";

// mock
// WARNING: `mockjs` NOT SUPPORT `IE` PLEASE DO NOT USE IN `production` ENV.
import "./mock";
import {
  SET_MAINAPP_UTILS,
  SET_MAIN_ROUTE,
  SET_MOCK,
  SET_SERVER_TIME_DIFF,
  SET_TOKEN,
  SET_USER_INFO,
} from "./store/mutation-types";

function createVueApp() {
  let instance: any = null;
  instance = createApp(App);
  loadPlugins(instance);
  instance.use(router).use(store);
  return instance;
}

let app: any = null; 

// 独立运行
if (!(window as any).__POWERED_BY_DUBHE__) {
  app = createVueApp();
  app.mount("#ceshi3");
}

const { mounted, activated, deactivated, destroyed } = initMicroVueApp({
  router,
  routePrefix: appSettings.dubhePrefix,
  mounted(el: any) {
    if (!(window as any).__POWERED_BY_DUBHE__) return;
    app = createVueApp();
    const child = document.createElement("div");
    // 开启shadow dom样式隔离模式
    el.shadowRoot.appendChild(child);
    // 关闭shadow dom样式隔离模式
    // el.appendChild(child);
    app.mount(child);
    if (registerMicroApp(appSettings.appName)) {
      subscribeGlobalStateChange((value: any) => {
        const {
          token,
          mainRoute,
          userInfo,
          serverTimeDiff,
          useMock,
          origin,
          utils,
          tabs,
          interceptorsCallback: { microAppRequestInterceptor, microAppResponseInterceptor },
        } = value;
        console.log("sub app origin", origin);
        store.commit(SET_TOKEN, token);
        store.commit(SET_MAIN_ROUTE, mainRoute);
        store.commit(SET_USER_INFO, userInfo);
        store.commit(SET_SERVER_TIME_DIFF, serverTimeDiff);
        store.commit("setTabs", tabs);
        store.commit(SET_MAINAPP_UTILS, {
          ...utils,
          microAppRequestInterceptor,
          microAppResponseInterceptor
        });
        if (
          process.env.NODE_ENV !== "production" ||
          process.env.VUE_APP_PREVIEW === "true"
        ) {
          store.commit(SET_MOCK, useMock);
        }
      });
    }
  },
  destroyed() {
    if (app) {
      app.unmount();
      resetStore();
      app = null;
    }
  },
});
const routePrefix = appSettings.dubhePrefix;

export { mounted, activated, deactivated, destroyed, router, routePrefix };
